package com.my.blog.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.blog.myblog.entity.Blackip;
import com.my.blog.myblog.service.BlackIpService;
import com.my.blog.utils.UserIpUtil;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/***
 *
 * @Auther: MuYun
 * @Date: 2021/10/8 15:39
 * @Description： 黑名单过滤
 *
 */
@WebFilter
public class IpFilter implements Filter {

    @Resource
    private BlackIpService blackIpService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //System.out.println("黑名单过滤启动..");
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //从请求中获取ip
        String ip = UserIpUtil.getIp(request);
        QueryWrapper<Blackip> queryWrapper=new QueryWrapper<>();
        List<Blackip> list = blackIpService.list(queryWrapper.lambda().eq(Blackip::getIp, ip));
        //没在黑名单里查到
        if(list.size()==0){
            //过去
            filterChain.doFilter(request,response);
            return;
        }else {
            //如果是黑名单，跳到/blackIp请求
            request.getRequestDispatcher("/blackIp").forward(request,response);
        }

    }

    @Override
    public void destroy() {

    }
}
